package cn.loioi.util;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

/**
 * <br>
 * (c) Copyright 2016 by <br>
 * @description :文本工具 <br>
 * @file_name :TextUtils.java <br>
 * @system_name :car-util <br>
 * @author :yyzh <br>
 * @创建时间 :2016年4月28日 下午3:52:55
 */
public class TextUtils extends StringUtils {
	private static final String REGEX = "(?<=(\\{\\{))([\\S\\s]*?)(?=(\\}\\}))";
	private static final String IS_NUMBER = "(^-?\\d*$)|(^-?\\d+\\.\\d+$)";

	/**
	 * 将模板格式化
	 * @param str 模板
	 * @param param 数据
	 * @return
	 */
	public static String templet(String str, Map<String, Object> param) {
		if (isEmpty(str)) return null;
		Pattern pattern = Pattern.compile(REGEX, Pattern.MULTILINE);
		Matcher matcher = pattern.matcher(str);
		while (matcher.find()) {
			str = str.replaceAll("\\{\\{" + matcher.group() + "\\}\\}", getValue(matcher.group(), param));
		}
		return str;
	}

	/**
	 * 生成随机 bits 位的纯数字
	 * @param bits
	 * @return
	 */
	public static String random(int bits) {
		return String.valueOf(Math.random()).substring(2, 2 + bits);
	}

	public static boolean isNumber(String str) {
		return test(IS_NUMBER, str);
	}

	/**
	 * 正则式校验
	 * @param regex 正则式
	 * @param str 待校验字符串
	 * @return
	 */
	public static boolean test(String regex, String str) {
		if (isEmpty(regex) || isEmpty(str)) return false;
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

	private static String getValue(String key, Map<String, Object> param) {
		if (key == null || param == null) return "";
		Object obj = param.get(key);
		if (obj == null) {
			return "";
		} else if (obj instanceof String) {
			return (String) obj;
		} else if (obj.getClass().isArray()) {
			return join((Object[]) obj, ",");
		} else if (obj instanceof List) {
			return join((List<?>) obj, ",");
		} else {
			return String.valueOf(obj);
		}
	}
}
